/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2021年5月26日
 */
package com.massyframework.beanskin.launcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.massyframework.beanskin.framework.Framework;
import com.massyframework.beanskin.framework.FrameworkConfig;
import com.massyframework.beanskin.framework.FrameworkFactory;
import com.massyframework.beanskin.launcher.deploying.DefaultLocalStoreFactory;
import com.massyframework.beanskin.launching.Launcher;
import com.massyframework.beanskin.launching.LaunchingHandler;
import com.massyframework.beanskin.util.IOUtils;
import com.massyframework.beanskin.util.localstore.LocalStore;
import com.massyframework.beanskin.util.sorting.OrderComparator;

/**
 * 代理启动器
 * @author huangkh
 *
 */
public class DefalutLauncher extends FrameworkConfigProcessing 
	implements Launcher {

	/* 缺省的配置文件路径 */
	private static final String DEFAULT_PATH = "META-INF/beanskin.default.properties";
    public  static final String CONFIG_PATH = "META-INF/beanskin.properties";
    private Logger logger = LoggerFactory.getLogger(DefalutLauncher.class);
    
	/**
	 * 
	 */
	public DefalutLauncher() {
	}

	@Override
	public Framework launch() throws Exception {
		return this.launch(null);
	}
		
	@Override
	public Framework launch(Map<String, String> override) throws Exception {
		//打印logo
		System.out.println(this.loadLogo());
		
		if (logger.isInfoEnabled()) {
			logger.info("launching Massy Framework...");
		}
		
		//加载默认的配置文件
		Map<String, String> configuration = this.loadDefaultConfiguration();
		if (override != null) {
			configuration.putAll(override);
		}
				
		FrameworkConfig config = this.createFrameworkConfig(configuration);
		ClassLoader classLoader = 
				config.getAttribute(ClassLoader.class.getName(), ClassLoader.class);
		FrameworkFactory factory =
				this.loadService(FrameworkFactory.class, classLoader);
		if (factory == null) {
			throw new RuntimeException("cannot load FrameworkFactory with spi.");
		}
		Framework result = this.createFramework(config, factory);		
		return result;
	}
	
	/**
	 * 创建运行框架
	 * @param config {@link FrameworkConfig}
	 * @param factory {@link FrameworkFactory}
	 * @return {@link Framework}
	 */
	protected Framework createFramework(FrameworkConfig config, FrameworkFactory factory) {
		List<LaunchingHandler> handlers = 
				this.loadServices(LaunchingHandler.class, this.getClass().getClassLoader());
		Collections.sort(handlers, new OrderComparator<>());
		this.initialize(handlers, config);
		
		return factory.createFramework(config);
	}

	/**
	 * 创建FrameworkConfig
	 * @return {@link FrameworkConfig}
	 */
	protected FrameworkConfig createFrameworkConfig(Map<String, String> configuration) {
		LocalStore localStore = this.createLocalStore(configuration);
		FrameworkConfig result = this.lookupFrameworkConfig(configuration, localStore);
		if (result == null) {
			throw new RuntimeException("cannot found Framework Runtime Core.");
		}
		
		boolean debug = this.runAtDebugModel();
		result.setParameter(Framework.DEBUG_MODEL, Boolean.toString(debug));
		
		return result;
	}
	
	/**
	 * 判断是否运行在调试模式
	 * @return {@link boolean}
	 */
	protected boolean runAtDebugModel() {
		List<String> args = ManagementFactory.getRuntimeMXBean().getInputArguments();
		for (String arg : args) {
		    if (arg.startsWith("-Xrunjdwp") || arg.startsWith("-agentlib:jdwp")) {
		        return true;
		    }
		}
		return false;
	}
	
	/**
	 * 创建本地存储
	 * @param configuration {@link Map}
	 * @return {@link LocalStore}
	 */
	protected LocalStore createLocalStore(Map<String, String> configuration) {
		DefaultLocalStoreFactory factory = new DefaultLocalStoreFactory();
		return factory.createLocalStore(configuration);
	}
	
	 /**
     * 加载图标
     * @return {@link StringBuilder}
     */
    protected StringBuilder loadLogo(){
        StringBuilder result = new StringBuilder();
        URL url = this.getClass().getClassLoader().getResource("META-INF/beanskin.logo");
        if (url != null){
            BufferedReader reader = null;
            String line = null;
            boolean top = true;
            try{
                reader = new BufferedReader(new InputStreamReader(url.openStream()));
                while ((line = reader.readLine()) != null){
                    if (!top){
                        result.append("\r\n");
                    }
                    result.append(line);
                    if (top){
                        top = false;
                    }
                }
            }catch(Exception e){

            }finally {
                IOUtils.close(reader);
            }
        }

        return result;
    }

	/**
     * 加载默认的配置文件
     * @return {@link Map}
     */
    protected Map<String, String> loadDefaultConfiguration(){
    	Map<String, String> result = new HashMap<>();
    	
    	ClassLoader loader = this.getClass().getClassLoader();
    	URL url = loader.getResource(DEFAULT_PATH);
    	this.doLoadConfiguration(url, result);
    	
    	url = loader.getResource(CONFIG_PATH);
    	this.doLoadConfiguration(url, result);
    	return result;
    }
    
    private void doLoadConfiguration(URL url, Map<String, String> configuration) {
    	if (url == null) return;
    	
    	InputStream is = null;
		try {
			is = url.openStream();
			Properties props = new Properties();
			props.load(is);
			
			Enumeration<Object> em = props.keys();
			while (em.hasMoreElements()) {
				String key = em.nextElement().toString();
				configuration.put(key, props.getProperty(key));
			}
		}catch(IOException e) {
			
		}finally {
			IOUtils.close(is);
		}
    }
}
